package com.pro01.apirednote.config;

import com.pro01.apirednote.mapper.ContentMapper;
import com.pro01.apirednote.pojo.Content;
import com.pro01.apirednote.service.ElasticsearchService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.client.Request;
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Slf4j
@Component
@RequiredArgsConstructor
public class ElasticsearchInitializer implements CommandLineRunner {

    private final ElasticsearchService elasticsearchService;
    private final ContentMapper contentMapper;
    private final RestClient restClient;
    private boolean elasticsearchAvailable = true;

    @Override
    public void run(String... args) {
        log.info("初始化ElasticSearch索引...");
        
        try {
            // 检查Elasticsearch是否可用
            checkElasticsearchAvailability();
            
            if (!elasticsearchAvailable) {
                log.warn("Elasticsearch不可用，跳过索引初始化");
                return;
            }
            
            // 创建索引
            elasticsearchService.createContentIndex();
            
            // 清空现有索引数据
            try {
                deleteAllDocuments("contents");
            } catch (Exception e) {
                log.error("清空索引数据失败", e);
                // 继续执行，尝试索引内容
            }
            
            // 同步现有数据
            List<Content> allContents = contentMapper.getAllContents();
            log.info("从数据库中获取到 {} 条内容记录", allContents.size());
            
            for (Content content : allContents) {
                if (Boolean.FALSE.equals(content.getIsDeleted())) {
                    elasticsearchService.indexContent(content);
                }
            }
            
            log.info("ElasticSearch索引初始化完成");
        } catch (Exception e) {
            log.error("初始化ElasticSearch索引失败", e);
        }
    }
    
    // 检查Elasticsearch是否可用
    private void checkElasticsearchAvailability() {
        try {
            Request request = new Request("GET", "/");
            Response response = restClient.performRequest(request);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                log.info("Elasticsearch连接成功");
                elasticsearchAvailable = true;
            } else {
                log.warn("Elasticsearch返回非200状态码: {}", statusCode);
                elasticsearchAvailable = false;
            }
        } catch (Exception e) {
            log.error("Elasticsearch连接失败: {}", e.getMessage());
            elasticsearchAvailable = false;
        }
    }
    
    // 删除索引中的所有文档
    private void deleteAllDocuments(String indexName) throws IOException {
        try {
            String deleteQuery = "{\"query\":{\"match_all\":{}}}";
            Request request = new Request("POST", "/" + indexName + "/_delete_by_query");
            request.setJsonEntity(deleteQuery);
            Response response = restClient.performRequest(request);
            log.info("清空索引数据结果: {}", response.getStatusLine().getStatusCode());
        } catch (IOException e) {
            log.error("清空索引数据失败", e);
            throw e;
        }
    }
} 